from fastapi import APIRouter, Body

from common.g.g import G_CLIENT
from common.pkg.ali.client import AliClient
from common.pkg.fastapi_util import cbv
from common.utils.resp import JsonResponse, RC
from common.route.tenant_route import ClientTenantBaseAPIRoute
from common.route.mall_route import MallMatchAPIRoute
from common.route.user_route import ClientMustLoginAPIRoute
from common.route.route import ZipCustomerRoute
from core.view import ClientBaseView, TenantBaseView
from schema.inner_use_schema.ali_pay_schema import AliPayTradeQueryRequestModel, AliPayTradeQueryResponseModel
from service.order_sercice import OrderService
from service.pay_way_service import TenantPayConfigService

router = APIRouter(prefix="/verification", route_class=ZipCustomerRoute(ClientTenantBaseAPIRoute, MallMatchAPIRoute, ClientMustLoginAPIRoute))


@cbv(router)
class ClientVerification(ClientBaseView):

    @router.post("/pay/ali/order")
    async def verification_ali_pay_order(self, order_sn: str = Body(..., embed=True)):
        oss = OrderService(self.mgw, self.redis)

        ok, data_or_code = await oss.get_order_info_for_check_pay(order_sn)
        if not ok:
            return self.unpack_response(ok, data_or_code)
        order = data_or_code.data
        # if order.mall_id != self.mall_id:
        #     return JsonResponse(code=RC.NOT_EXIST, msg="订单不存在").to_response()

        tpcs = TenantPayConfigService(self.mgw, self.redis)
        ok, data_or_code = await tpcs.get_tenant_ali_pay_config(self.tenant_id)
        if not ok:
            return self.unpack_response(ok, data_or_code)
        ali_client = AliClient(client=G_CLIENT, **data_or_code.data)
        ok, res = await ali_client.trade_pay_query(AliPayTradeQueryRequestModel(out_trade_no=order_sn))
        if ok:
            resp_model = AliPayTradeQueryResponseModel(**res)
            if resp_model.trade_status == "TRADE_SUCCESS":
                ok, data_or_code = await oss.order_pay_by_ali(self.tenant_id, order.order_id, order.version, resp_model)
                return self.unpack_response(ok, data_or_code)
        else:
            return JsonResponse(code=RC.INTER_ERROR, msg="获取支付结果失败").to_response()


@cbv(router)
class TenantVerification(TenantBaseView):
    ...

